package com.chenyanqing.config;

import com.chenyanqing.io.Resources;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.annotation.Resource;
import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

public class XMLConfigBuilder {



    private  Configuration  configuration;

    public XMLConfigBuilder(){
        this.configuration = new Configuration();
    }


    /**
     * 使用dom4j对配置文件进行解析
     * @param in
     * @return
     */
    public  Configuration  parseConfig(InputStream in ) throws Exception {
        Document document = new SAXReader().read(in);
        Element element = document.getRootElement();


        //解析数据源
        List<Element> list = element.selectNodes("//property");
        //存储 key-value结构
        Properties properties = new Properties();
        //遍历
        for (Element ele : list) {
            String name = ele.attributeValue("name");
            String value = ele.attributeValue("value");
            properties.setProperty(name,value);
        }
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        this.configuration.setDataSource(comboPooledDataSource);


        //解析mapper.xml  拿到路径--字节输入流--进行dom4j解析
        List<Element> mapperLocations = element.selectNodes("//mapperLocations");
        if(mapperLocations!=null && mapperLocations.size()>0){
            Element location = mapperLocations.get(0);
            String mapperLocationPath = location.attributeValue("location");
            //进行目录解析和包扫描  解析mapper.xml文件
            InputStream []resourceAsStreams = Resources.getResources(mapperLocationPath);

            if(resourceAsStreams!=null && resourceAsStreams.length>0) {
                for (InputStream resourceAsStream : resourceAsStreams) {
                    XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
                    xmlMapperBuilder.parseMapper(resourceAsStream);
                }
            }


        }
        return this.configuration;

    }
}
